import { v4 as uuidv4 } from 'uuid';
import { db } from "./db";

export class ProjectService {
    static async list(kw?: string) {
        const temp: ProjectItem[] = await db.projects
            .filter(p => p.name.includes(kw || '') || p.description?.includes(kw || '') || p.author?.includes(kw || ''))
            .limit(100)
            .toArray();
        return temp.sort((a, b) => (b.installTime || 0) - (a.installTime || 0))
    }

    static getId() {
        return uuidv4()
    }

    static async one(id: string) {
        return await db.projects.get(id)
    }

    static async save(data: ProjectItem) {
        const temp = await db.projects.get(data.id);
        data.loading = false;
        if (temp) {
            await db.projects.update(data.id, {
                ...data
            })
        } else {
            await db.projects.add(data)
        }
    }

    static async saveAll(data: ProjectItem[]) {
        data.forEach(p => {
            this.save(p)
        })
    }

    static async remove(id: string) {
        await db.projects.delete(id);
    }

    static async plugins(_id: string) {
        return db.projects.filter(p => {
            return p.type === 'editorPlugin' && p.enabled
        }).toArray()
    }
}
